package com.firewolf.rocketmq;

import java.util.List;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
 * 指定消息进入哪个Message Queue
 */
public class SettingProducer {

  public static void main(String[] args) throws Exception {
    //创建生产者，指定所在的组
    DefaultMQProducer producer = new
        DefaultMQProducer("producer-group1");
    //指定nameserver，如果有多个，用;隔开
    producer.setNamesrvAddr("10.211.55.6:9876");
    //启动生产者
    producer.start();
    //发送消息
    for (int i = 0; i < 20; i++) {
      //创建要发送的消息对象
      Message msg = new Message("mytopic" /* Topic */,
          "TagA" /* Tag */,
          ("Hello RocketMQ " +
              i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
      );
      //发送消息
      SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
        public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
          return mqs.get(0);
        }
      }, null);
      System.out.printf("%s%n", sendResult);
    }
    //关闭生产者
    producer.shutdown();
  }

}
